package Cau13;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

public class RegisterImpl extends UnicastRemoteObject implements Iregister {

	private static final long serialVersionUID = 1L;
	String pathfile;
	FileInputStream fis;
	FileOutputStream fos;
	ArrayList<Account> danhsach=null;
	public RegisterImpl(String pathfile) throws RemoteException
	{
		this.pathfile=pathfile;
		danhsach=getAccountList();
	}

	@Override
	public boolean register(Account acc) throws RemoteException {
		if(!CheckUsernameExisted(acc.getUserName()))
			if(SaveAcount(acc))
				return true;
		return false;
	}

	@Override
	public boolean signIn(Account acc) throws RemoteException {
		if(CheckLogin(acc))return true;
		return false;
	}

	@Override
	public ArrayList<Account> getAccountList() throws RemoteException {
		
		try {
			ArrayList<Account>temp=new ArrayList<Account>();
			File f=new File(pathfile);
			BufferedReader br = new BufferedReader(new FileReader(f));
			String []ds;
			String s;
			while((s=br.readLine())!=null)
			{
				ds=s.split("#");
				
				temp.add(new Account(ds[0], ds[1]));
			}
			br.close();
			return temp;
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();			
		}
		catch(IOException ex)		{
			ex.printStackTrace();			
		}
		return null;
	}
	public boolean SaveAcount(Account a)
	{
		//ghi file
		String s=a.getUserName()+"#"+a.getPassword();		
		try {
			FileOutputStream os = new FileOutputStream("D:/acount.txt", true);
			PrintWriter pr = new PrintWriter(os);
			pr.println(s);
			pr.close();
			os.close();			
			danhsach.add(a);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
			return false;
		}
	}
	
	public boolean CheckLogin(Account acc)
	{
		boolean re=false;
		for(int i=0;i<danhsach.size();i++)
		{
			if((danhsach.get(i).getUserName().equalsIgnoreCase(acc.getUserName()))&&(danhsach.get(i).getPassword().equalsIgnoreCase(acc.getPassword())))
			{
				
				return true;
			}
		}
		return re;		
	}
	
	public boolean CheckUsernameExisted(String username)
	{
		boolean re=false;
		for(int i=0;i<danhsach.size();i++)
		{
			if(danhsach.get(i).getUserName().equalsIgnoreCase(username))
			{
				return true;
			}
		}
		return re;
		
	}

	

}
